#include "chattabbedwidget.h"
#include "ui_chattabbedwidget.h"

ChatTabbedWidget::ChatTabbedWidget(QWidget *parent, IcyBuddies *fBuddies,
                                   IcySettings *fSettings) :
    QWidget(parent),
    ui(new Ui::ChatTabbedWidget)
{
    ui->setupUi(this);
    buddies = fBuddies;
    settings = fSettings;
    setVisible(false);

    setWindowIcon(settings->getIcon("system://message"));
}

ChatTabbedWidget::~ChatTabbedWidget()
{
    delete ui;
    delete chatWidget;
}

void ChatTabbedWidget::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

_fastcall qint32 ChatTabbedWidget::getIndex(const QString &sSN, const bool bAbs)
{
    qint32 iCount = buddies->count();

    if ( bAbs ){
        for ( qint32 i = 0; i < iCount; i++ ){
            if ( buddies->at(i)->screenName() == sSN)
                return i;
        }
    }else{
        for ( qint32 i = 0; i < iCount; i++ ){
            if ( buddies->at(i)->screenName() == sSN && buddies->at(i)->index() != -1)
                return buddies->at(i)->index();
        }
    }
    return -1;
}

_fastcall qint32 ChatTabbedWidget::getIndex(const qint32 iIndex)
{
    qint32 iCount = buddies->count();
    for ( qint32 i = 0; i < iCount; i++ ){
        if ( buddies->at(i)->index() != -1 )
            return i;
    }
    return -1;
}

_fastcall void ChatTabbedWidget::addWidget(const QString &sSN, const QString &sAlias)
{
    if ( !isVisible() )
        setVisible(true);

    qint32 iIndex = getIndex(sSN, false);

    if ( iIndex != -1 ){
        ui->tabWidget->setCurrentIndex(iIndex);
        return;
    }

    ui->tabWidget->addTab(new ChatWidget(0, settings, sSN, sAlias), sAlias);
    iIndex = getIndex(sSN, true);
    if ( iIndex != -1 ){
        buddies->at(iIndex)->setIndex(ui->tabWidget->count() - 1);
        ui->tabWidget->setTabIcon(ui->tabWidget->currentIndex(),
                                  buddies->at(iIndex)->statusIcon());
    }
    setWindowTitle("IcyQt - Chat Window (" + sAlias + ')');
}

void ChatTabbedWidget::on_tabWidget_tabCloseRequested(int index)
{
    qint32 iIndex = getIndex(index);
    if ( iIndex != -1 )
        buddies->at(iIndex)->setIndex(-1);
    delete (ui->tabWidget->widget(index));
    ui->tabWidget->removeTab(index);
    if ( ui->tabWidget->count() < 1 )
        close();
}
